package com.zhike.common.utils;

import java.time.Duration;

import javax.annotation.PostConstruct;

import com.zhike.common.constant.RedisKey;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Component
@Slf4j
public class RedisFactory {
    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.username}")
    private String username;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.database}")
    private int database;

    private static Jedis jedis = null;
    private static JedisPool pool = null;

    @Bean
    public void connection() throws Exception {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(30);
        config.setMaxIdle(0);
        config.setMaxWait(Duration.ofMillis(10000));

        pool = new JedisPool(config, host, port, 2000, username, password, database);
        jedis = pool.getResource();
    }

    /**
     * 获取jedis
     *
     * @return
     * @throws Exception
     */
    public static Jedis getJedis() throws Exception {
        if (pool == null) {
            throw new Exception("get Jedis fail");
        }
        return pool.getResource();
    }

    public static void disConnection() {
        if (jedis != null) {
            jedis.close();
            jedis.disconnect();
            jedis = null;
        }
        if (pool != null) {
            pool.close();
            pool = null;
        }
        log.info("close redis ok");
    }

    /**
     * 清除在redis的会话
     *
     * @param uid
     */
    public static void cleanSession(String uid) {
        Jedis jedis = null;
        try {
            jedis = RedisFactory.getJedis();
            jedis.del(RedisKey.sessionStore(uid));
            log.info("cleanSession ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }
}
